package edu.pku.sei.gefcommon.descriptor.descriptors;


import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.views.properties.PropertyDescriptor;

import edu.pku.sei.gefcommon.descriptor.annotation.DescriptorConstance;


public class EnumerationPropertyDescriptor extends PropertyDescriptor {
	private Object[] values = DescriptorConstance.EMPTY_STRING_ARRAY;
	private String[] strings = DescriptorConstance.EMPTY_STRING_ARRAY;
	public EnumerationPropertyDescriptor(Object id, String name,String catalog) {
		super(id, name);
		//this.setValues(DescriptorConstance.EMPTY_STRING_ARRAY);
		this.setCategory(catalog);
	}
	
	
	
	@Override
	public CellEditor createPropertyEditor(Composite parent) {
		ComboBoxCellEditor editor = new ComboBoxCellEditor(parent, getStrings());
		return editor;
	}

	@Override
	public ILabelProvider getLabelProvider() {
		ILabelProvider lp = super.getLabelProvider();
		if (lp == null || !(lp instanceof EnumerationLabelProvider)) {
			lp = new EnumerationLabelProvider(this);
			this.setLabelProvider(lp);
		}
		return lp;
	}

	public Integer fromModel(String value){
		int i,s = getStrings().length;
		for(i=0;i<s;i++) {
			String o = getStrings()[i];
			if(o.equals(value)) return i;
		}
		return -1;
	}
	public String toModel(Integer value){
		if(value<0||value>getStrings().length) return "null";
		return getStrings()[value];
	}
	public Integer fromObjModel(Object value){
		if(value instanceof String)return 0;
		int i,s = getValues().length;
		for(i=0;i<s;i++) {
			Object o = getValues()[i];
			//modified by Yang Yuanzu. "o == value" has been changed to "o.equals(value)";
			if(o.equals(value)) return i+1;
		}
		return 0;
	}
	public Object toObjModel(Integer value){
		if(value<=0||value>getValues().length) return null;
		return getValues()[value-1];
	}


	public void setValues(Object[] values) {
		assert values instanceof String[];
		
		this.values = values;
		this.strings = new String [values.length];
		for(int i=0; i<values.length; i++) {
			strings[i] = values[i].toString();
		}
	}
	public void setObjectValues(Object[] values){
		this.values = values;
		this.strings = new String [values.length+1];
		strings[0] = "null";
		for(int i=0; i<values.length; i++) {
			strings[i+1] = values[i].toString();
		}
	}

	public String[] getStrings() {
		return strings;
	}

	public Object[] getValues() {
		return values;
	}
}
